package com.yami.shop.sys.multishop.adapter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.common.config.Constant;
import com.yami.shop.security.common.adapter.SignAuthAdapter;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.enums.SysTypeEnum;
import com.yami.shop.sys.common.dao.ShopEmployeeMapper;
import com.yami.shop.sys.common.model.ShopEmployee;
import com.yami.shop.sys.common.service.ShopMenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * @author lgh on 2018/09/07.
 */
@Service
@AllArgsConstructor
public class MultishopSignAuthAdapter implements SignAuthAdapter {
    private final ShopMenuService shopMenuService;
    private final ShopEmployeeMapper shopEmployeeMapper;

    @Override
    public UserInfoInTokenBO loadUserInfoInToken(Map<String, Object> dataMap) {

        UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
        String shopIdStr = dataMap.get("shopId").toString();

        // 默认为自营店
        long shopId = Constant.MAIN_SHOP;
        if (StrUtil.isNotBlank(shopIdStr)) {
            shopId = Long.valueOf(shopIdStr);
        }

        ShopEmployee shopEmployee = shopEmployeeMapper.selectOne(new LambdaQueryWrapper<ShopEmployee>()
                .eq(ShopEmployee::getShopId, shopId)
                .eq(ShopEmployee::getType, 0)
        );
        userInfoInToken.setUserId(shopEmployee.getEmployeeId().toString());
        userInfoInToken.setSysType(SysTypeEnum.MULTISHOP.value());
        userInfoInToken.setEnabled(shopEmployee.getStatus() == 1);
        userInfoInToken.setShopId(shopEmployee.getShopId());
        userInfoInToken.setOtherId(shopEmployee.getEmployeeId());
        userInfoInToken.setPerms(shopMenuService.getShopPermissions(shopEmployee));
        return userInfoInToken;
    }
}
